package jsjf;

import jsjf.exceptions.*;
import java.util.Arrays;
import java.util.Stack;


public class ArrayStack<T> implements StackADT<T>{
    private final int DEFAULT_CAPACITY = 100;

    private int top;
    private T[] stack;

    // 使用默认容量创建一个空栈
    public ArrayStack()
    {
        top = 0;
        stack = (T[]) (new Object[DEFAULT_CAPACITY]);
    }

    // 使用指定容量创建一个空栈，参数initialCapacity表示的是指定容量
    public ArrayStack (int initialCapacity)
    {
        top = 0;
        stack = (T[]) (new Object[initialCapacity]);
    }

    public void push (T element)
    {
        if (size() == stack.length)
        {
            expandCapacity();
        }
        stack[top] = element;
        top++;
    }

    public int size() {
        return top;
    }

    private void expandCapacity()
    {
        stack = Arrays.copyOf(stack, stack.length * 2);
    }

    public T pop() throws EmptyCollectionException
    {
        if (isEmpty())
            throw new EmptyCollectionException("Stack");
        top--;
        T result = stack[top];
        stack[top] = null;

        return  result;
    }

    public boolean isEmpty() {
        if(stack[0] == null)
        {
            return true;
        }
        return false;
    }


    public T peek() throws EmptyCollectionException
    {
        if (isEmpty())
            throw new EmptyCollectionException("Stack");

        return stack[top - 1];
    }

    public String toString()
    {
        String a = "";
        for (int x = 0;x < top; x++)
        {
            a += stack[x] + " ";

        }
        return a;
    }
}
